package org.tale.mscp.ctreport.contorller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.calcite.linq4j.Linq4j;
import org.apache.calcite.linq4j.function.Predicate1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.tale.mscp.ctreport.dao.AttendanceSetting;
import org.tale.mscp.ctreport.entity.AjaxFormat;
import org.tale.mscp.ctreport.entity.AttendanceSetting.CalendarData;
import org.tale.mscp.ctreport.entity.AttendanceSetting.WorkDay;
import org.tale.mscp.ctreport.entity.AttendanceSetting.WorkDayType;
import org.tale.mscp.ctreport.entity.AttendanceSetting.WorkType;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by cwb on 2015/9/13.
 */
@Controller
@RequestMapping(value = "/setting")
@Slf4j
public class AttendanceSettingController {
    @Autowired
    private AttendanceSetting attendanceSetting;
    Gson gson = new Gson();

    @RequestMapping(value = "/getworkday")
    public String GetWorkDay() {
        return "WorkDay";
    }


    @RequestMapping(value = "/getworktype")
    @ResponseBody
    public String GetWorkType() {
        List<WorkType> lwt = attendanceSetting.getWorkType();
        AjaxFormat af = new AjaxFormat();
        if (lwt != null) {
            af.SetResult(AjaxFormat.ResultEnum.success);
            af.SetResultDesc("正确返回");
            af.SetJsonContent(lwt);
        } else {
            af.SetResult(AjaxFormat.ResultEnum.fail);
            af.SetResultDesc("读取失败");
        }
        return gson.toJson(af);
    }

    @RequestMapping(value = "getworkdata")
    @ResponseBody
    public String GetWorkData(String start, String end) {

        try {
            List<CalendarData> lcd = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date stDate = sdf.parse(start);
            Date edDate;
            Calendar dataCalendar = Calendar.getInstance();
            dataCalendar.setTime(stDate);
            if (dataCalendar.get(Calendar.DAY_OF_MONTH) != 1) {
                dataCalendar.add(dataCalendar.MONTH, 1);
                dataCalendar.set(Calendar.DAY_OF_MONTH, 1);
            }
            Calendar eddataCalendar = Calendar.getInstance();
            eddataCalendar.setTime(dataCalendar.getTime());
            eddataCalendar.add(dataCalendar.MONTH, 1);
            //dataCalendar.set(Calendar.DAY_OF_MONTH, 1);
/*            Date edDate=sdf.parse(end);
            Calendar eddataCalendar = Calendar.getInstance();
            eddataCalendar.setTime(edDate);
            eddataCalendar.set(Calendar.DAY_OF_MONTH, 1);
            edDate = eddataCalendar.getTime();

            int MonthDays=eddataCalendar.get(Calendar.DAY_OF_YEAR)-dataCalendar.get(Calendar.DAY_OF_YEAR);*/

            stDate = dataCalendar.getTime();
            edDate = eddataCalendar.getTime();
            List<WorkDayType> lwd = attendanceSetting.getWorkDays(stDate, edDate);
            if (lwd != null && lwd.size() > 0) {
                for (WorkDayType workDay_type : lwd) {
                    CalendarData calendarData = new CalendarData();
                    calendarData.setTypeId(workDay_type.getTypeId());
                    calendarData.setTitle(workDay_type.getType());
                    calendarData.setAllDay(true);
                    calendarData.setStart(sdf.format(workDay_type.getWorkDay()));
                    calendarData.setRemark(workDay_type.getRemark());
                    lcd.add(calendarData);
                }
            } else {
                //region 无工作日数据是采取的初始化方法
                int MonthDays = dataCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);// 获取选择月份的天数
                // 将结束日期
                //dataCalendar.add(dataCalendar.MONTH, 1);
                // edDate = dataCalendar.getTime();
                List<String> WorkDays = new ArrayList<>();
                List<String> WeekendDays = new ArrayList<>();
                WorkDays.add(sdf.format(dataCalendar.getTime()));

                for (int i = 0; i < MonthDays - 1; i++) {
                    dataCalendar.add(dataCalendar.DATE, 1);
                    int weekday = dataCalendar.get(Calendar.DAY_OF_WEEK);//1为周日
                    if (weekday == 1 || weekday == 7) {
                        WeekendDays.add(sdf.format(dataCalendar.getTime()));
                    } else {
                        WorkDays.add(sdf.format(dataCalendar.getTime()));
                    }
                }
                List<WorkType> lwt = attendanceSetting.getWorkType();
                for (String workDay : WorkDays) {
                    CalendarData calendarData = new CalendarData();
                    List<WorkType> noarmalList = (
                            Linq4j.asEnumerable(lwt).where(new Predicate1<WorkType>() {
                                @Override
                                public boolean apply(WorkType workType) {
                                    if (workType.getRemark().equals("normal"))
                                        return true;
                                    else
                                        return false;
                                }
                            }).toList());
                    if (noarmalList.size() > 0) {
                        WorkType workType = noarmalList.get(0);
                        calendarData.setTypeId(workType.getId());
                        calendarData.setTitle(workType.getType());
                        calendarData.setAllDay(true);
                        calendarData.setStart(workDay);
                        calendarData.setRemark(workType.getRemark());
                        lcd.add(calendarData);
                    }

                }
                for (String weekend : WeekendDays) {
                    CalendarData calendarData = new CalendarData();
                    List<WorkType> restList = (
                            Linq4j.asEnumerable(lwt).where(new Predicate1<WorkType>() {
                                @Override
                                public boolean apply(WorkType workType) {
                                    if (workType.getRemark().equals("rest"))
                                        return true;
                                    else
                                        return false;
                                }
                            }).toList());
                    if (restList.size() > 0) {
                        WorkType workType = restList.get(0);
                        calendarData.setTypeId(workType.getId());
                        calendarData.setTitle(workType.getType());
                        calendarData.setAllDay(true);
                        calendarData.setStart(weekend);
                        calendarData.setRemark(workType.getRemark());
                        lcd.add(calendarData);
                    }

                }
                //endregion
            }


            return gson.toJson(lcd);
        } catch (ParseException e) {
            return "";
        }
    }

    @RequestMapping(value = "saveworkday")
    @ResponseBody
    @Transactional
    public String SaveWorkDay(String json, String stdate, String eddate) {
        AjaxFormat af = new AjaxFormat();
        List<CalendarData> lcd = gson.fromJson(json, new TypeToken<List<CalendarData>>() {
        }.getType());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date stDate = null;
        try {
            stDate = sdf.parse(stdate);
            Date edDate = sdf.parse(eddate);
            List<WorkDay> lwd = new ArrayList<>();
            for (CalendarData calendarData : lcd) {
                Date workDaty = sdf.parse(calendarData.getStart());
                WorkDay wd = new WorkDay();
                wd.setTypeId(calendarData.getTypeId());
                wd.setWorkDay(workDaty);
                lwd.add(wd);
            }
            attendanceSetting.deleteWorkDay(stDate, edDate);
            boolean rs = attendanceSetting.setWorkDay(lwd);
            af.SetResult(AjaxFormat.ResultEnum.success);
            af.SetResultDesc("新增成功");
            af.SetJsonContent(rs);

        } catch (ParseException e) {
            e.printStackTrace();
            af.SetResult(AjaxFormat.ResultEnum.fail);
            af.SetResultDesc("新增失败");
        } catch (Exception ex) {
            af.SetResult(AjaxFormat.ResultEnum.fail);
            af.SetResultDesc("新增失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            return gson.toJson(af);
        }
    }
}
